use anyhow::Ok;
use rand::seq::SliceRandom;

const UPPER: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ";

const LOWER: &[u8] = b"abcdefghijkmnpqrstuvwxyz";

const NUMBER: &[u8] = b"123456789";

const SYMBOL: &[u8] = b"!@#$%^&*_";

/// 处理生成随机数的函数
pub fn process_genpass(
    length: u8,
    uppercase: bool,
    lowercase: bool,
    number: bool,
    symbol: bool,
) -> anyhow::Result<String> {
    let mut password = Vec::new();
    let mut chars = Vec::new();
    let mut rng = rand::thread_rng();
    // 如果是大写 字符串则从大写字母中获取
    if uppercase {
        chars.extend_from_slice(UPPER);
        password.push(*UPPER.choose(&mut rng).expect(""));
    }
    //  如果是小写 字母从小写字母序列中获取
    if lowercase {
        chars.extend_from_slice(LOWER);
        password.push(*LOWER.choose(&mut rng).expect(""));
    }
    //  如果是数值 则从数值序列中获取
    if number {
        chars.extend_from_slice(NUMBER);
        password.push(*NUMBER.choose(&mut rng).expect(""));
    }
    //   如果是特殊字符则从特殊字符序列中获取
    if symbol {
        chars.extend_from_slice(SYMBOL);
        password.push(*SYMBOL.choose(&mut rng).expect(""));
    }
    for _ in 0..(length - password.len() as u8) {
        let c = chars
            .choose(&mut rng)
            .expect("chars won't be empty in this context");
        password.push(*c);
    }
    password.shuffle(&mut rng);
    let pwd = String::from_utf8(password)?;
    let pwd = pwd.trim();
    Ok(pwd.to_string())
}
